package com.sl.auth.modular.login.service.impl;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.dao.SaTokenDaoDefaultImpl;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Page;
import cn.hutool.db.sql.Order;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.SerializerFactory;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.sl.auth.modular.login.entity.SaTokenDO;
import com.sl.auth.modular.login.service.SaTokenDaoService;
import lombok.SneakyThrows;
import org.apache.commons.lang3.SerializationException;
import org.springframework.cache.support.NullValue;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;


@Component
public class SaTokenAuthImpl extends SaTokenDaoDefaultImpl implements SaTokenDao {

    private final SaTokenDaoService saTokenDaoService;

    private SaGenericJackson2JsonDbSerializer saGenericJackson2JsonDbSerializer = new SaGenericJackson2JsonDbSerializer();

    public SaTokenAuthImpl(SaTokenDaoService saTokenDaoService) {
        this.saTokenDaoService = saTokenDaoService;
        initRefreshThread();
    }
    // ------------------------ String 读写操作

    @SneakyThrows
    @Override
    public String get(String key) {
        clearKeyByTimeout(key);


        SaTokenDO bySaKey = saTokenDaoService.getBySaKey(key);
//        Entity entity = DbUtil.use(dataSource).queryOne("select sa_key,sa_value from " + TABLE_NAME + " where sa_key = ? and delete_flag = ?", key, CommonDeleteFlagEnum.NOT_DELETE.getValue());
        if (ObjUtil.isNull(bySaKey)) {
            return null;
        }
        String value = bySaKey.getSaValue();
        return value;
    }

    @SneakyThrows
    @Override
    public void set(String key, String value, long timeout) {
        if (timeout == 0 || timeout <= SaTokenDao.NOT_VALUE_EXPIRE) {
            return;
        }
        long l = (timeout == SaTokenDao.NEVER_EXPIRE) ? (SaTokenDao.NEVER_EXPIRE) : (System.currentTimeMillis() + timeout * 1000);


        SaTokenDO saTokenDO = new SaTokenDO();
        saTokenDO.setTimeout(l);
        saTokenDO.setSaKey(key);
        saTokenDO.setSaValue(value);
        boolean save = saTokenDaoService.save(saTokenDO);

    }

    @SneakyThrows
    @Override
    public void update(String key, String value) {
        long keyTimeout = getKeyTimeout(key);
        if (keyTimeout == SaTokenDao.NOT_VALUE_EXPIRE) {
            return;
        }
        String s = get(key);
        if (StrUtil.isBlank(s)) {
            this.set(key, value, keyTimeout);
        } else {
            saTokenDaoService.updateValueByKey(value, key);
        }
    }

    @SneakyThrows
    @Override
    public void delete(String key) {
        saTokenDaoService.deleteByKey(key);
    }

    @Override
    public long getTimeout(String key) {
        return getKeyTimeout(key);
    }

    @SneakyThrows
    @Override
    public void updateTimeout(String key, long timeout) {
        long l = (timeout == SaTokenDao.NEVER_EXPIRE) ? (SaTokenDao.NEVER_EXPIRE) : (System.currentTimeMillis() + timeout * 1000);

        saTokenDaoService.updateTimeoutByKey(l, key);
//        DbUtil.use(dataSource).execute("update " + TABLE_NAME + " set timeout = ? where sa_key = ? and delete_flag", l, key,
//                CommonDeleteFlagEnum.NOT_DELETE.getValue());
    }


    // ------------------------ Object 读写操作

    @SneakyThrows
    @Override
    public Object getObject(String key) {
        clearKeyByTimeout(key);
        String value = this.get(key);
        if (StrUtil.isBlank(value)) {
            return null;
        }
        byte[] decode = Base64.decode(value);
        Object deserialize = saGenericJackson2JsonDbSerializer.deserialize(decode);

        return deserialize;
//        if (StrUtil.startWith(value, "class:")) {
//            String className = StrUtil.subBetween(value, "class:", "@");
//            String json = StrUtil.replace(value, "class:" + className + "@", "");
//           return JsonUtil.toBean(json, ClassUtil.loadClass(className));
//        }
//        return JsonUtil.toObj(value);
    }

    @SneakyThrows
    @Override
    public void setObject(String key, Object object, long timeout) {
        if (timeout == 0 || timeout <= SaTokenDao.NOT_VALUE_EXPIRE) {
            return;
        }
        long l = (timeout == SaTokenDao.NEVER_EXPIRE) ? (SaTokenDao.NEVER_EXPIRE) : (System.currentTimeMillis() + timeout * 1000);
//        String str = JsonUtil.toStr(object);

        byte[] serialize = saGenericJackson2JsonDbSerializer.serialize(object);

        String encode = Base64.encode(serialize);
//        str = StrUtil.concat(true, "class:", object.getClass().getName(), "@", str);
//        SaSession
        SaTokenDO saTokenDO = new SaTokenDO();
        saTokenDO.setTimeout(l);
        saTokenDO.setSaKey(key);
        saTokenDO.setSaValue(encode);
        saTokenDaoService.save(saTokenDO);
    }

    @SneakyThrows
    @Override
    public void updateObject(String key, Object object) {
        long keyTimeout = getKeyTimeout(key);
        if (keyTimeout == SaTokenDao.NOT_VALUE_EXPIRE) {
            return;
        }
        Object s = getObject(key);
        if (ObjUtil.isNull(s)) {
            this.setObject(key, object, keyTimeout);
        } else {
//            String str = JsonUtil.toStr(object);
//            str = StrUtil.concat(true, "class:", object.getClass().getName(), "@", str);
            byte[] serialize = saGenericJackson2JsonDbSerializer.serialize(object);

            String encode = Base64.encode(serialize);
            saTokenDaoService.updateValueByKey(encode, key);
//            DbUtil.use(dataSource).execute("update " + TABLE_NAME + " set sa_value = ? where sa_key = ?", encode, key);
        }
        // dataMap.put(key, object);
    }

    @SneakyThrows
    @Override
    public void deleteObject(String key) {
        saTokenDaoService.deleteByKey(key);
//        DbUtil.use(dataSource).execute("delete from " + TABLE_NAME + " where sa_key = ? and delete_flag = ?", key, CommonDeleteFlagEnum.NOT_DELETE.getValue());
    }

    @Override
    public long getObjectTimeout(String key) {
        return getKeyTimeout(key);
    }

    @SneakyThrows
    @Override
    public void updateObjectTimeout(String key, long timeout) {
        long l = (timeout == SaTokenDao.NEVER_EXPIRE) ? (SaTokenDao.NEVER_EXPIRE) : (System.currentTimeMillis() + timeout * 1000);

        saTokenDaoService.updateTimeoutByKey(l, key);
//        DbUtil.use(dataSource).execute("update " + TABLE_NAME + " set timeout = ? where sa_key = ?", l, key);
    }


    // ------------------------ Session 读写操作
    // 使用接口默认实现


    // ------------------------ 过期时间相关操作

    /**
     * 如果指定key已经过期，则立即清除它
     *
     * @param key 指定key
     */
    @SneakyThrows
    void clearKeyByTimeout(String key) {
//        long keyTimeout = this.getKeyTimeout(key);
        Long expirationTime = getDbTimeout(key);
        // 清除条件：如果不为空 && 不是[永不过期] && 已经超过过期时间
        if (expirationTime != null && expirationTime != SaTokenDao.NEVER_EXPIRE && expirationTime < System.currentTimeMillis()) {
//            dataMap.remove(key);
//            expireMap.remove(key);
            this.delete(key);
        }
    }

    @SneakyThrows
    private Long getDbTimeout(String key) {
        SaTokenDO bySaKey = saTokenDaoService.getBySaKey(key);
//        Entity entity = DbUtil.use(dataSource).queryOne("select timeout from " + TABLE_NAME + " where sa_key = ? and delete_flag = ?", key, CommonDeleteFlagEnum.NOT_DELETE.getValue());
        if (ObjUtil.isNull(bySaKey)) {
            return null;
        }
        Long expirationTime = bySaKey.getTimeout();
        return expirationTime;
    }

    /**
     * 获取指定key的剩余存活时间 (单位：秒)
     */
    long getKeyTimeout(String key) {
        // 先检查是否已经过期
        clearKeyByTimeout(key);
        // 获取过期时间
        Long expire = getDbTimeout(key);
        // 如果根本没有这个值
        if (expire == null) {
            return SaTokenDao.NOT_VALUE_EXPIRE;
        }
        // 如果被标注为永不过期
        if (expire == SaTokenDao.NEVER_EXPIRE) {
            return SaTokenDao.NEVER_EXPIRE;
        }
        // ---- 计算剩余时间并返回
        long timeout = (expire - System.currentTimeMillis()) / 1000;
        // 小于零时，视为不存在
        if (timeout < 0) {
//            dataMap.remove(key);
//            expireMap.remove(key);
            this.delete(key);
            return SaTokenDao.NOT_VALUE_EXPIRE;
        }
        return timeout;
    }


    // --------------------- 定时清理过期数据

    /**
     * 执行数据清理的线程
     */
    public Thread refreshThread;

    /**
     * 是否继续执行数据清理的线程标记
     */
    public volatile boolean refreshFlag;


    @SneakyThrows
    /**
     * 清理所有已经过期的key
     */ public void refreshDataMap() {
        if (ObjUtil.isNull(saTokenDaoService)) {
            return;
        }
        List<SaTokenDO> saTokenDOS = saTokenDaoService.queryValidKey();
            if(CollUtil.isEmpty(saTokenDOS)){
                return;
            }
        for (SaTokenDO entity : saTokenDOS) {
            clearKeyByTimeout(entity.getSaKey());
        }
    }

    /**
     * 初始化定时任务
     */
    public void initRefreshThread() {

        // 如果配置了<=0的值，则不启动定时清理
        if (SaManager.getConfig().getDataRefreshPeriod() <= 0) {
            return;
        }
        // 启动定时刷新
        this.refreshFlag = true;
        this.refreshThread = new Thread(() -> {
            for (; ; ) {
                try {
                    try {
                        // 如果已经被标记为结束
                        if (refreshFlag == false) {
                            return;
                        }
                        // 执行清理
                        refreshDataMap();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // 休眠N秒
                    int dataRefreshPeriod = SaManager.getConfig().getDataRefreshPeriod();
                    if (dataRefreshPeriod <= 0) {
                        dataRefreshPeriod = 1;
                    }
                    Thread.sleep(dataRefreshPeriod * 1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        this.refreshThread.start();
    }

    /**
     * 结束定时任务
     */
//    @Override
//    public void endRefreshThread() {
//        this.refreshFlag = false;
//    }


    // --------------------- 会话管理
    @SneakyThrows
    @Override
    public List<String> searchData(String prefix, String keyword, int start, int size, boolean sortType) {
        Page page = new Page();
        page.setPageSize(size);
        page.setPageNumber(size);
        page.setOrder(new Order("sa_key"));
        //todo 需要分页
        List<SaTokenDO> saTokenDOS = saTokenDaoService.queryBySearchKey(keyword);
//        PageResult<Entity> page1 = DbUtil.use(dataSource).page("select sa_key from " + TABLE_NAME + " where sa_key like '?%' and sa_key like '%?%'", page, prefix, keyword);
        return saTokenDOS.stream().map(SaTokenDO::getSaKey).collect(Collectors.toList());
//        return SaFoxUtil.searchList(expireMap.keySet(), prefix, keyword, start, size, sortType);
    }


//    @Override
//    public void run(ApplicationArguments args) throws Exception {
////        DbUtil.use(dataSource).ta
//        Table tableMeta = MetaUtil.getTableMeta(dataSource, TABLE_NAME);
//        Collection<Column> columns = tableMeta.getColumns();
//        if (CollUtil.isEmpty(columns)) {
//            createTable();
//        }
//        //创建表
//    }

    public static class SaGenericJackson2JsonDbSerializer {

        private final ObjectMapper mapper;

        /**
         *
         */
        public SaGenericJackson2JsonDbSerializer() {
            this((String) null);
        }

        /**
         * given {@literal name}. In case of an {@literal empty} or {@literal null} String the default
         * {@link JsonTypeInfo.Id#CLASS} will be used.
         *
         * @param classPropertyTypeName Name of the JSON property holding type information. Can be {@literal null}.
         */
        public SaGenericJackson2JsonDbSerializer(@Nullable String classPropertyTypeName) {
            this(new ObjectMapper());

            // simply setting {@code mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)} does not help here since we need
            // the type hint embedded for deserialization using the default typing feature.
            registerNullValueSerializer(mapper, classPropertyTypeName);

            if (StringUtils.hasText(classPropertyTypeName)) {
                mapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.NON_FINAL, classPropertyTypeName);
            } else {
                mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
            }

            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        }

        /**
         * Setting a custom-configured {@link ObjectMapper} is one way to take further control of the JSON serialization
         * process. For example, an extended {@link SerializerFactory} can be configured that provides custom serializers for
         * specific types.
         *
         * @param mapper must not be {@literal null}.
         */
        public SaGenericJackson2JsonDbSerializer(ObjectMapper mapper) {
            Assert.notNull(mapper, "ObjectMapper must not be null!");
            this.mapper = mapper;
        }

        /**
         * {@code classPropertyTypeName}. This method should be called by code that customizes
         *
         * @param objectMapper          the object mapper to customize.
         * @param classPropertyTypeName name of the type property. Defaults to {@code @class} if {@literal null}/empty.
         * @since 2.2
         */
        public static void registerNullValueSerializer(ObjectMapper objectMapper, @Nullable String classPropertyTypeName) {

            // simply setting {@code mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)} does not help here since we need
            // the type hint embedded for deserialization using the default typing feature.
            objectMapper.registerModule(new SimpleModule().addSerializer(new NullValueSerializer(classPropertyTypeName)));
        }

        /*
         * (non-Javadoc)
         * @see org.springframework.data.redis.serializer.RedisSerializer#serialize(java.lang.Object)
         */
        public byte[] serialize(@Nullable Object source) throws SerializationException {

            if (source == null) {
                return new byte[0];
            }

            try {
                return mapper.writeValueAsBytes(source);
            } catch (JsonProcessingException e) {
                throw new SerializationException("Could not write JSON: " + e.getMessage(), e);
            }
        }

        /*
         * (non-Javadoc)
         * @see org.springframework.data.redis.serializer.RedisSerializer#deserialize(byte[])
         */
        public Object deserialize(@Nullable byte[] source) throws SerializationException {
            return deserialize(source, Object.class);
        }

        /**
         * @param source can be {@literal null}.
         * @param type   must not be {@literal null}.
         * @return {@literal null} for empty source.
         * @throws SerializationException
         */
        @Nullable
        public <T> T deserialize(@Nullable byte[] source, Class<T> type) throws SerializationException {

            Assert.notNull(type,
                    "Deserialization type must not be null! Please provide Object.class to make use of Jackson2 default typing.");

            if ((source == null || source.length == 0)) {
                return null;
            }

            try {
                return mapper.readValue(source, type);
            } catch (Exception ex) {
                throw new SerializationException("Could not read JSON: " + ex.getMessage(), ex);
            }
        }

        /**
         * {@link StdSerializer} adding class information required by default typing. This allows de-/serialization of
         * {@link NullValue}.
         *
         * @author Christoph Strobl
         * @since 1.8
         */
        private static class NullValueSerializer extends StdSerializer<NullValue> {

            private static final long serialVersionUID = 1999052150548658808L;
            private final String classIdentifier;

            /**
             * @param classIdentifier can be {@literal null} and will be defaulted to {@code @class}.
             */
            NullValueSerializer(@Nullable String classIdentifier) {

                super(NullValue.class);
                this.classIdentifier = StringUtils.hasText(classIdentifier) ? classIdentifier : "@class";
            }

            /*
             * (non-Javadoc)
             * @see com.fasterxml.jackson.databind.ser.std.StdSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider)
             */
            @Override
            public void serialize(NullValue value, JsonGenerator jgen, SerializerProvider provider)
                    throws IOException {

                jgen.writeStartObject();
                jgen.writeStringField(classIdentifier, NullValue.class.getName());
                jgen.writeEndObject();
            }
        }
    }

}
